//
//  GKDYPlayerManager.m
//  GKDYVideo
//
//  Created by QuintGao on 2023/3/17.
//  Copyright © 2023 QuintGao. All rights reserved.
//

#import "GKDYPlayerManager.h"
#import <AFNetworking/AFNetworking.h>
#import <ZFPlayer/ZFPlayer.h>
#import <ZFPlayer/ZFAVPlayerManager.h>
#import "GKDYVideoCell.h"
#import "GKDYVideoPortraitCell.h"
#import "WSPlayerRequest.h"

@interface GKDYPlayerManager()<GKVideoScrollViewDataSource, GKDYVideoScrollViewDelegate, GKDYVideoPortraitCellDelegate>
@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, assign) BOOL isSeeking;
@end

@implementation GKDYPlayerManager
- (instancetype)init {
    if (self = [super init]) {
        [self initPlayer];
    }
    return self;
}

- (void)dealloc {
    NSLog(@"GKDYPlayerManager dealloc");
    [self stop];
}

- (void)initPlayer {
    // 初始化播放器
    ZFAVPlayerManager *manager = [[ZFAVPlayerManager alloc] init];
    manager.shouldAutoPlay = NO; // 自動播放
    ZFPlayerController *player = [[ZFPlayerController alloc] init];
    player.currentPlayerManager = manager;
    player.disableGestureTypes = ZFPlayerDisableGestureTypesPan | ZFPlayerDisableGestureTypesPinch;
    player.allowOrentitaionRotation = NO; // 禁止自動旋转
    self.player = player;
    WeakSelf
    // 播放结束回调
    player.playerDidToEnd = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset) {
        if (weakSelf.isPlayNext == YES){
            [weakSelf.scrollView scrollToNextPage];
        }else{
            [weakSelf.player.currentPlayerManager replay];
        }
    };
    
    // 播放失敗回调
    player.playerPlayFailed = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, id  _Nonnull error) {
        weakSelf.portraitView.playBtn.hidden = NO;
    };
    // 加载状态
    player.playerLoadStateChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, ZFPlayerLoadState loadState) {
        if ((loadState == ZFPlayerLoadStatePrepare || loadState == ZFPlayerLoadStateStalled) && weakSelf.player.currentPlayerManager.isPlaying) {
            [weakSelf.portraitView.slider showLoading];
        }else {
            [weakSelf.portraitView.slider hideLoading];
        }
    };
    // 播放时间
    player.playerPlayTimeChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSTimeInterval currentTime, NSTimeInterval duration) {
        [weakSelf.portraitView.slider updateCurrentTime:currentTime totalTime:duration];
    };
}


- (BOOL)isPlaying {
    return self.player.currentPlayerManager.isPlaying;
}

- (void)playVideoWithVideo:(WSVideo *)object {
    NSInteger index = -1;
    if (self.dataSources.count > 0) {
        index = 0;
    }
    for (int i = 0; i < self.dataSources.count; i ++) {
        WSVideo * video = self.dataSources[i];
        if (video.id == object.id) {
            index = i;
            break;
        }
    }
    
    if (index >= 0) {
        self.scrollView.defaultIndex = index;
        [self.scrollView reloadData];
    }
}

- (void)playVideoWithCell:(GKDYVideoCell *)cell index:(NSInteger)index {
    WSVideo *model = self.dataSources[index];
    self.currentCell = (GKDYVideoPortraitCell *)cell;
    self.portraitView = self.currentCell.portraitView;
    // 设置播放內容视图
    if (self.player.containerView != cell.coverImgView) {
        self.player.containerView = cell.coverImgView;
    }
    // 设置播放器控制层视图
    GKDYVideoPortraitCell *portraitCell = (GKDYVideoPortraitCell *)cell;
    if (self.player.controlView != portraitCell.portraitView) {
        self.player.controlView = portraitCell.portraitView;
        self.portraitView = portraitCell.portraitView;
    }
    // 设置封面图片
    id<ZFPlayerMediaPlayback> manager = self.player.currentPlayerManager;
    [manager.view.coverImageView sd_setImageWithURL:[NSURL URLWithString:model.cover] placeholderImage:WSVideoPlaceholderImage];
    if (model.url.length > 0) {
        // 播放內容一致，不做处理
        if ([self.player.assetURL.absoluteString isEqualToString:model.url]) return;
        // 设置播放地址
        self.player.assetURL = [NSURL URLWithString:model.url];
        
        self.portraitView.playBtn.hidden = YES;
        if (self.isAppeared) {
            [self.player.currentPlayerManager play];
        }
    }
    if (!model.isRequestForFavorite) {
        [self loadFavoriteWithObject:model];
    }
    if ([self.delegate respondsToSelector:@selector(cellDidScroll2Video:)]) {
        [self.delegate cellDidScroll2Video:model];
    }
    NSLog(@"dataSources.count:%ld", (long)self.dataSources.count);
    NSLog(@"index:%ld", (long)index);
    if (model == [self.dataSources lastObject]) {
        [self.scrollView.mj_footer beginRefreshing];
    }
    
}

- (void)loadFavoriteWithObject:(WSVideo *)object {
    [WSPlayerRequest loadcharonTV_FavoriteWithChapter_id:object.id success:^(NSInteger integer) {
        object.isLike = integer == 1;
        object.isRequestForFavorite = YES;
        if (self.portraitView.model.id == object.id) {
            self.currentCell.portraitView.model = object;
        }
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)stopPlayWithCell:(GKDYVideoCell *)cell index:(NSInteger)index {
    WSVideo *model = self.dataSources[index];
    if (![self.player.assetURL.absoluteString isEqualToString:model.url]) return;
    
    [self.player stop];
    if ([self.player.controlView isKindOfClass:GKDYVideoPortraitView.class]) {
        [self.player.controlView removeFromSuperview];
        self.player.controlView = nil;
    }
    [cell resetView];
}

- (void)play {
    if (self.isPlaying) return;
    [self.player.currentPlayerManager play];
    self.portraitView.playBtn.hidden = YES;
}

- (void)pause {
    if (!self.isPlaying) return;
    [self.player.currentPlayerManager pause];
}

- (void)stop {
    [self.player.currentPlayerManager stop];
    self.player = nil;
}

#pragma mark - Private
- (void)likeVideoWithModel:(WSVideo *)model {
    if (model == nil) {
        model = self.currentCell.model;
    }
    model.isLike = YES;
    [self.scrollView reloadData];
}

#pragma mark - GKVideoScrollViewDataSource
- (NSInteger)numberOfRowsInScrollView:(GKVideoScrollView *)scrollView {
    return self.dataSources.count;
}

- (GKVideoViewCell *)scrollView:(GKVideoScrollView *)scrollView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WSVideo *model = self.dataSources[indexPath.row];
    GKDYVideoPortraitCell *cell = [scrollView dequeueReusableCellWithIdentifier:@"GKDYVideoPortraitCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.manager = self;
    cell.portraitView.slider.player = self.player;
    [cell loadData:model];
    return cell;
}

#pragma mark - GKDYVideoScrollViewDelegate
- (void)scrollView:(GKVideoScrollView *)scrollView didEndScrollingCell:(GKVideoViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self playVideoWithCell:(GKDYVideoCell *)cell index:indexPath.row];
}

- (void)scrollView:(GKVideoScrollView *)scrollView didEndDisplayingCell:(GKVideoViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self stopPlayWithCell:(GKDYVideoCell *)cell index:indexPath.row];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        if (self.scrollView.currentIndex == 0 && scrollView.contentOffset.y < 0) {
            self.scrollView.contentOffset = CGPointZero;
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.portraitView willBeginDragging];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self.portraitView didEndDragging];
}

#pragma mark - GKDYVideoPortraitCellDelegate
- (void)videoCell:(GKDYVideoPortraitCell *)cell didClickLike:(WSVideo *)model {
    if ([self.delegate respondsToSelector:@selector(cellDidClickLike:)]) {
        [self.delegate cellDidClickLike:model];
    }
}

- (void)videoCell:(GKDYVideoPortraitCell *)cell didClickChapter:(nonnull WSVideo *)model {
    if ([self.delegate respondsToSelector:@selector(cellDidClickChapter:)]) {
        [self.delegate cellDidClickChapter:model];
    }
}

#pragma mark - Lazy
- (GKDYVideoScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[GKDYVideoScrollView alloc] init];
        _scrollView.dataSource = self;
        _scrollView.delegate = self;
        _scrollView.backgroundColor = UIColor.blackColor;
        [_scrollView registerClass:GKDYVideoPortraitCell.class forCellReuseIdentifier:@"GKDYVideoPortraitCell"];
        [_scrollView addPanGesture];
    }
    return _scrollView;
}

- (NSMutableArray *)dataSources {
    if (!_dataSources) {
        _dataSources = [NSMutableArray array];
    }
    return _dataSources;
}

@end
